package com.cao.service;

import com.alibaba.fastjson.JSON;
import com.cao.pojo.Content;
import com.cao.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: huahua
 * @Date: 2021-04-13 23:08
 */
@Service
public class JdService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //解析数据放入es中
    public boolean parseContent(String keywords) throws IOException {
        List<Content> contents = new HtmlParseUtils().JDParse(keywords);
        //把得到的内容入库
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("jd_goods")
                            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !bulk.hasFailures();

    }

    //从es中查询数据
    public List<Map<String, Object>> searchPage(Integer from, Integer size, String keywords) throws IOException {
        if (from <= 1) {
            from = 1;
        }
        //条件搜索
        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //分页
        builder.from(from);
        builder.size(size);

        //精确查找时
        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("title", keywords);
        builder.query(queryBuilder);
        //延时
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //关闭多个高亮
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);

        //执行搜索
        request.source(builder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析
        ArrayList<Map<String, Object>> list = new ArrayList<>();

        for (SearchHit hit : search.getHits().getHits()) {

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title!=null){
                Text[] fragments = title.fragments();
                String newTitle = "";

                for (Text fragment : fragments) {
                    newTitle+=fragment;
                }

                sourceAsMap.put("title",newTitle);
            }
            list.add(sourceAsMap);


        }
        return list;
    }
}
